package block

import (
	"bytes"
	"errors"
	bolt "github.com/github-boltdb-master"
)

type ChainIterator struct {
	//数据库，从这个数据库中获取数据的
	DB *bolt.DB
	//标志位：表达当前迭代到哪一个区块的
	CurrentHash []byte
}
//找区块
func (iterator *ChainIterator)Next()(*Block,error){
	var block *Block
	var err error
	err = iterator.DB.View(func(tx *bolt.Tx) error {
		bk:= tx.Bucket([]byte(BUCKET_BLOCK))
		if bk == nil{
			return errors.New("没有桶1")
		}
		blockBytes := bk.Get(iterator.CurrentHash)
		block, err = DeSerialize(blockBytes)
		if err != nil{
			return err
		}
		iterator.CurrentHash = block.PrevHash
		return nil
	})
	return block,err
}
//判断是还有上一个区块
func(iterator *ChainIterator)HasNext()bool{
	int := bytes.Compare(iterator.CurrentHash, nil)
	if int == 0{
		return false
	}
	return int != 0
}